package crypt;

import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.security.*;
import org.apache.commons.codec.binary.Base64;
/**
 * Utility class that handles signing of a message
 * 
 * @author jonas.lindmark
 */
public class SignHandler {
    public byte[] sig;
    public byte[] body;
    /**
     * Signs given message
     * 
     * @param msg Mesasge to be signed
     * @param pkfile Private file
     * @return String representation encoded in base64 of the signature.
     */
    public String sign(String msg, String pkfile){
        try {
            ObjectInputStream in = new ObjectInputStream(new FileInputStream(pkfile));
            PrivateKey pk = (PrivateKey)in.readObject();
            in.close();
            
            Signature sign = Signature.getInstance("SHA1withDSA");
            sign.initSign(pk);
            byte[] bmsg = msg.getBytes();
            body = bmsg;
            byte[] signature = new byte[1024/8];

            sign.update(bmsg);
            sign.sign(signature,0,signature.length);
            String res = new String(Base64.encodeBase64(signature),"ASCII");
            sig = signature;
            return res;

        } catch (Exception e) {
            System.out.println(e);
            e.printStackTrace();
            return "";
        }
    }
}
